package com.adnaan.backend.utils;

import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * author: adnaan
 * create: 2025-02-17 13:53
 * Description:
 */

@Component
public class HttpJsonRequestUtil {

    private final RestTemplate restTemplate;

    public HttpJsonRequestUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 发送GET请求并返回JSON响应
     *
     * @param url          请求的URL
     * @param responseType 响应类型
     * @param <T>          泛型类型
     * @return 响应对象
     */
    public <T> T get(String url, Class<T> responseType) {
        return restTemplate.getForObject(url, responseType);
    }

    /**
     * 发送POST请求并返回JSON响应
     *
     * @param url          请求的URL
     * @param requestBody  请求体
     * @param responseType 响应类型
     * @param <T>          泛型类型
     * @return 响应对象
     */
    public <T> T post(String url, Object requestBody, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, entity, responseType);
        return response.getBody();
    }

    /**
     * 发送PUT请求并返回JSON响应
     *
     * @param url          请求的URL
     * @param requestBody  请求体
     * @param responseType 响应类型
     * @param <T>          泛型类型
     * @return 响应对象
     */
    public <T> T put(String url, Object requestBody, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.PUT, entity, responseType);
        return response.getBody();
    }

    /**
     * 发送DELETE请求并返回JSON响应
     *
     * @param url          请求的URL
     * @param responseType 响应类型
     * @param <T>          泛型类型
     * @return 响应对象
     */
    public <T> T delete(String url, Class<T> responseType) {
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.DELETE, null, responseType);
        return response.getBody();
    }
}
